package cn.lxh.basic.controller;


import cn.lxh.basic.exception.BusinessException;
import cn.lxh.basic.utils.FastdfsUtil;
import cn.lxh.org.basic.utils.AjaxResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true)  MultipartFile file) throws IOException {
        try {
            String filename = file.getOriginalFilename();//sadfasd/sadf/1.jpeg
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastdfsUtil.upload(file.getBytes(),extName);
            return AjaxResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }
    @DeleteMapping              //  http://localhost:8080/fastDfs?path=/group1/M00/00/04/CgAIC2Kln6SAEh72AAD1vLo2Ruw09.jpeg
    public AjaxResult delete(@RequestParam String path) throws BusinessException {
        try {
            String pathTmp = path.substring(1);//  group1/M00/00/04/CgAIC2Kln6SAEh72AAD1vLo2Ruw09.jpeg
            String group = pathTmp.substring(0,pathTmp.indexOf("/"));//   group1
            String filename = pathTmp.substring(pathTmp.indexOf("/")+1);//   M00/00/04/CgAIC2Kln6SAEh72AAD1vLo2Ruw09.jpeg
            FastdfsUtil.delete(group,filename);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }


}
